package Algorithm.KMP;

//暴力匹配字符串
public class ViolenceMatch {
	public static void main(String[] args) {
		String str1 = "BBC ABCDAB ABCDABCDABDE";
		String str2 = "ABCDABD";
		System.out.println("匹配到的首字符下标" + violenceMatch(str1, str2));
	}

	//暴力匹配算法实现
	public static int violenceMatch(String str1, String str2) {
		char[] s1 = str1.toCharArray();
		char[] s2 = str2.toCharArray();

		int s1Length = s1.length;
		int s2Length = s2.length;

		int i = 0;//指向 s1 的索引
		int j = 0;//指向 s2 的索引

		int times = 0;//匹配次数

		while (i < s1Length && j < s2Length) {
			times++;
			if (s1[i] == s2[j]) {//匹配成功
				i++;
				j++;
			} else {
				//匹配失败，令 i 退回开始匹配的第一个字符的下一个字符
				//即i= i-(j-1), j = 0
				i = i - (j - 1);
				j = 0;
			}
		}
		System.out.println("匹配次数:" + times);
		//根据 j 来判断是否匹配成功
		if (j == s2Length) {
			//若成功，返回匹配到的字符串的首字符的下标
			return i - j;
		} else {
			//没有匹配到
			return -1;
		}
	}
}
